#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
@Date   : 2019/11/30

"""
import requests
from requests.exceptions import ConnectionError, ConnectTimeout
from mmonitor.common.vars import HTTP_TIMEOUT_CODE, HTTP_DNS_CODE


def request_get_url(url):
    """

    :param url:
    :return: 状态码，错误信息，延迟(默认0代表访问失败）
    """
    status_code = 0
    duration = 0
    res, error = _get_url(url)
    if res is not None:
        status_code = res.status_code
        duration = '%.2f' % (float(res.elapsed.microseconds) / 1000000)
    return status_code, error, duration


def _get_url(url):
    res, error = None, 0
    try:
        res = requests.get(url=url)
    except ConnectTimeout:
        error = HTTP_TIMEOUT_CODE
    except ConnectionError as e:
        try:
            if "nodename nor servname provided" in e.message.status.errorMessage:
                error = HTTP_DNS_CODE
        except AttributeError:
            error = HTTP_TIMEOUT_CODE
    return res, error


if __name__ == "__main__":
    status_code, error, duration = request_get_url("http://wwwww.jiankong.art")
    print(status_code, error, duration)
